package com.platform.common.utils.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * ChannelSupervise 实体类，用于储存客户端channel连接信息
 */
public class ChannelSupervise {
    // channel连接组
    private static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //定义channelid 的map信息
    private static ConcurrentMap<String, ChannelId> ChannelMap = new ConcurrentHashMap();

    /**
     * 获取channel组
     * @return
     */
    public static ChannelGroup getChannelGroup() {
        return GlobalGroup;
    }


    /**
     * 保存channel信息
     * @param channel
     */
    public static void addChannel(Channel channel){
        GlobalGroup.add(channel);
        ChannelMap.put(channel.id().asLongText(),channel.id());
    }

    /**
     * 移除channel信息
     * @param channel
     */
    public static void removeChannel(Channel channel){
        GlobalGroup.remove(channel);
        ChannelMap.remove(channel.id().asLongText());
    }

    /**
     * 根据channelid查找channel信息
     * @param id
     * @return
     */
    public static Channel findChannel(String id){
        ChannelId channelId = ChannelMap.get(id);
        if(channelId!=null){
            Channel channel = GlobalGroup.find(ChannelMap.get(id));
            return channel;
        }else{
            return null;
        }
    }
}
